//
// Created by bt110 on 2019/8/19.
//
#include "loger.h"
using  namespace Loger;
string getTimeDate() {
    time_t timep;
    time (&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d",localtime(&timep) );
    return string(tmp);
}

string getTime(){ 
    time_t timep;
    time (&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );
    return string(tmp);
}

int _C_Loger::Debug(string dat,string  function,int line){
        // 还没有过天
    if(getTimeDate() == this->mCurrentDate){
        string tmp = getTime();
        tmp += ": ";
        tmp += dat;
        tmp += "at    [" + function + " line " + std::to_string(line) + "]";
        tmp += "\n";
        int ret =fwrite(tmp.c_str(),tmp.size(),1,this->mFile);
        fflush(this->mFile);
        return ret;
    }else{    // 已经过天了
        this->mCurrentDate = getTimeDate();
        string path = getTimeDate() + ".log";
        this->mFile = fopen(path.c_str(),"w+");
        if (this->mFile == nullptr){
            this->error = true;
        }
        string tmp = getTime();
        tmp += ": ";
        tmp += dat;
        tmp += "at    [" + function + " line " + std::to_string(line) + "]";
        tmp += "\n";
        int ret = fwrite(tmp.c_str(),tmp.size(),1,this->mFile);
        fflush(this->mFile);
        return ret;
    }
    return 0;
}

void _C_Loger::operator<<(const string& wb)  {
    // 还没有过天
    if(getTimeDate() == this->mCurrentDate) {
        string tmp = getTime();
        tmp += ":";
        tmp += wb;
        tmp += " \n";
        fwrite(tmp.c_str(),tmp.size(),1,this->mFile);
        fflush(this->mFile);
    }else{    // 已经过天了
        this->mCurrentDate = getTimeDate();
        string path = getTimeDate() + ".log";
        this->mFile = fopen(path.c_str(),"w+");
        if (this->mFile == nullptr){
            this->error = true;
        }

        string tmp = getTime();
        tmp += ":";
        tmp += wb;
        tmp += " \n";
        fwrite(tmp.c_str(),tmp.size(),1,this->mFile);
        fflush(this->mFile);
    }
}

bool file_existed(string path) {
    fstream _file;
    _file.open(path.c_str(),ios::in);
    if(!_file)  {
        return false;
    }
    else  {
        _file.close();
        return true;
    }
}

_C_Loger::_C_Loger(FILE *p) {
    this->mFile = p;
    this->mCurrentDate = getTime();
}

_C_Loger::_C_Loger(string path) {
    this->mCurrentDate = getTimeDate();
    this->mCurrentPath = path + this->mCurrentDate;
    this->mFile = fopen(this->mCurrentPath.c_str(),"a+");
    if(! this->mFile){
        fprintf(stderr,"error open log files %s code %d,please check file path",this->mCurrentPath.c_str(),errno);
        exit(0);
    }else{
        
    }
}